﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.CodeDom;

using System.CodeDom.Compiler;
using System.Reflection;
using Newtonsoft.Json;
using Microsoft.VisualStudio.TextTemplating;
using T5.TextTemplating;
using NetCore.Model;
using NetCore.BLL;
using NetCore;
using NetCore.Code.Model;
using NetCore.Code.BLL;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {

            ApplicationEnvironments.Site = ConfigHelper.GetAppSettings<SiteConfig>("SiteConfig");
            ApplicationEnvironments.DefaultSession = new ApplicationSession();
            ApplicationEnvironments.ProviderType = (ProviderType)Enum.Parse(typeof(ProviderType), ApplicationEnvironments.Site.ProviderType);

            // DataParameterCollection dataParameters = new DataParameterCollection(ProviderType.SqlServer);
            //InitDataService initDataService = new InitDataService();
            //initDataService.Init();

            string outcontent = "";
          //  string outfile1 = null;
            NetCore.Code.BLL.DbCodeService dbCodeService = new DbCodeService();
            Dictionary<string, string> dicCode = new Dictionary<string, string>();
            var startDate = DateTime.Now;
            Console.WriteLine(startDate.ToString("yyyy-MM-dd HH:mm:ss"));
            //dbCodeService.CreateCodes("1,2,3,4", "201812261412481248154", ref outcontent, 0);
            string rootPath = ApplicationEnvironments.BaseDirectory+ApplicationEnvironments.TempPath+"code/";
            //if (dicCode != null && dicCode.Count > 0)
            //{
            //    foreach (var item in dicCode)
            //    {
            //        FileHelper.WriteLine(rootPath + item.Key,item.Value);
            //    }
            //}
            if (File.Exists(ApplicationEnvironments.BaseDirectory + ApplicationEnvironments.TempPath + "code.zip"))
            {
                File.Delete(ApplicationEnvironments.BaseDirectory + ApplicationEnvironments.TempPath + "code.zip");
            }
            //System.IO.Compression.ZipFile.CreateFromDirectory(rootPath,
            //    ApplicationEnvironments.BaseDirectory + ApplicationEnvironments.TempPath + "code.zip", System.IO.Compression.CompressionLevel.Optimal, true);
           Console.WriteLine(outcontent);
            var endDate = DateTime.Now;
            Console.WriteLine(endDate.ToString("yyyy-MM-dd HH:mm:ss"));
            TimeSpan ts1 = new TimeSpan(startDate.Ticks);
            TimeSpan ts2 = new TimeSpan(endDate.Ticks);
            TimeSpan ts3 = ts1.Subtract(ts2).Duration();
            Console.WriteLine(ts3.Seconds);

            //ProcessInstanceService processInstance = new ProcessInstanceService();
            //processInstance.GetFlow("WF009", 0, true);
            //string strError = "";
            //string instanceId = "";
            // FlowParameterCollection valuePairs = new FlowParameterCollection();
            //      valuePairs.Add("submit", "1");
            //processInstance.Start("WF009", 0, "111111111111112", "测试流程", ApplicationEnvironments.DefaultSession.UserId, valuePairs, ref instanceId, ref strError);

            //valuePairs["Submit"] = "1";
            // valuePairs.Add("Submit", "1");
            //  processInstance.Run("20181215151352135208302532142",
            //     valuePairs, LinkTypeEnum.Submit, ApplicationEnvironments.DefaultSession.UserId, "fsafdasf", ref strError);

            Console.ReadKey();
        }


        public class ApplicationSession : IApplicationSession
        {
            public string UserId => "10000000000000004";

            public string UserName => throw new NotImplementedException();

            public string IPAddress => throw new NotImplementedException();

            public string FormAddress => throw new NotImplementedException();

            public string ServerAddress => throw new NotImplementedException();

            public string UserToken => throw new NotImplementedException();

            public T GetUser<T>() where T : class, new()
            {
                throw new NotImplementedException();
            }

            public void SetToken(string value)
            {
                throw new NotImplementedException();
            }
        }
    }
    public class DummyHost : ITextTemplatingEngineHost
    {
        public readonly Dictionary<string, string> Locations = new Dictionary<string, string>();
        public readonly Dictionary<string, string> Contents = new Dictionary<string, string>();
        public readonly Dictionary<string, object> HostOptions = new Dictionary<string, object>();
        List<string> standardAssemblyReferences = new List<string>();
        List<string> standardImports = new List<string>();
        public readonly CompilerErrorCollection Errors = new CompilerErrorCollection();
        public readonly Dictionary<string, Type> DirectiveProcessors = new Dictionary<string, Type>();
        string outputFile;
        public virtual object GetHostOption(string optionName)
        {
            object o;
            HostOptions.TryGetValue(optionName, out o);
            return o;
        }

        public virtual bool LoadIncludeText(string requestFileName, out string content, out string location)
        {
            content = null;
            return Locations.TryGetValue(requestFileName, out location)
                && Contents.TryGetValue(requestFileName, out content);
        }

        public virtual void LogErrors(CompilerErrorCollection errors)
        {
            Errors.AddRange(errors);
        }

        public virtual AppDomain ProvideTemplatingAppDomain(string content)
        {
            return null;
        }

        public virtual string ResolveAssemblyReference(string assemblyReference)
        {
            if (System.IO.Path.IsPathRooted(assemblyReference))
                return assemblyReference;
            foreach (string referencePath in StandardAssemblyReferences)
            {
                var path = System.IO.Path.Combine(referencePath, assemblyReference);
                if (System.IO.File.Exists(path))
                    return path;
            }

            var assemblyName = new AssemblyName(assemblyReference);
            if (assemblyName.Version != null)//Load via GAC and return full path
                return Assembly.Load(assemblyName).Location;

            if (!assemblyReference.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && !assemblyReference.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
                return assemblyReference + ".dll";
            return assemblyReference;
        }

        public virtual Type ResolveDirectiveProcessor(string processorName)
        {
            Type t;
            DirectiveProcessors.TryGetValue(processorName, out t);
            return t;
        }

        public virtual string ResolveParameterValue(string directiveId, string processorName, string parameterName)
        {
            throw new System.NotImplementedException();
        }

        public virtual string ResolvePath(string path)
        {
            throw new System.NotImplementedException();
        }

        public virtual void SetFileExtension(string extension)
        {
            extension = extension.TrimStart('.');
            if (Path.HasExtension(outputFile))
            {
                outputFile = Path.ChangeExtension(outputFile, extension);
            }
            else
            {
                outputFile = outputFile + "." + extension;
            }
        }

        public virtual void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective)
        {
            throw new System.NotImplementedException();
        }

        public virtual IList<string> StandardAssemblyReferences
        {
            get { return standardAssemblyReferences; }
        }

        public virtual IList<string> StandardImports
        {
            get { return standardImports; }
        }

        public virtual string TemplateFile
        {
            get; set;
        }
    }
}
